package com.tutk.P2PCam264;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.tutk.IOTC.Camera;
import com.tutk.IOTC.st_LanSearchInfo;
import com.tutk.agza.AgzaPushUtil;

import java.util.ArrayList;
import java.util.List;

import cn.innosmart.aq.R;
import cn.innosmart.qrcode.view.CaptureActivity;

import static com.tutk.P2PCam264.MainActivity.CameraList;

public class AddDeviceActivity extends AppCompatActivity {

	private final int REQUEST_CODE_GETUID_BY_SCAN_BARCODE = 0;

	private EditText edtUID;
	private EditText edtSecurityCode;
	private EditText edtName;
	private Button btnScan;
	private Button btnSearch;
	private Button btnOK;
	private Button btnCancel;
	private ResultStateReceiver resultStateReceiver;
	private IntentFilter filter;
	private ThreadTPNS thread;

	// private final static String ZXING_DOWNLOAD_URL = "http://zxing.googlecode.com/files/BarcodeScanner3.72.apk";
	// private final static String ZXING_DOWNLOAD_URL = "http://www.tutk.com/IOTCApp/Android/BarcodeScanner.apk";
	private final static String ZXING_DOWNLOAD_URL = "http://push.iotcplatform.com/release/BarcodeScanner.apk";

	private List<SearchResult> list = new ArrayList<SearchResult>();
	
	
	private ProgressDialog pdialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle(getText(R.string.dialog_AddCamera));
		setContentView(R.layout.add_device);

        filter=new IntentFilter();
        filter.addAction(AddDeviceActivity.class.getName());
        resultStateReceiver=new ResultStateReceiver();
        
        registerReceiver(resultStateReceiver, filter);
		
		edtUID = (EditText) findViewById(R.id.edtUID);
		edtSecurityCode = (EditText) findViewById(R.id.edtSecurityCode);
		edtName = (EditText) findViewById(R.id.edtNickName);

		btnScan = (Button) findViewById(R.id.btnScan);
		btnScan.setOnClickListener(btnScanClickListener);
		btnSearch = (Button) findViewById(R.id.btnSearch);
		btnSearch.setOnClickListener(btnSearchOnClickListener);
		btnOK = (Button) findViewById(R.id.btnOK);
		btnOK.setOnClickListener(btnOKOnClickListener);
		btnCancel = (Button) findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(btnCancelOnClickListener);

		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {

		if (requestCode == REQUEST_CODE_GETUID_BY_SCAN_BARCODE) {

			if (resultCode == RESULT_OK) {
				String contents = intent.getStringExtra("QRCODERESULT");
				// String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
				if ( null == contents){
					Bundle bundle = intent.getExtras();
				    if (null != bundle) {
				      /* String */contents = bundle.getString("result");
				    }
				}
				if( null == contents){
					return;
				}
				    
				if(contents.length() > 20){
					String temp = "";
				
					for(int t = 0;t<contents.length();t++){
						if(contents.substring(t, t+1).matches("[A-Z0-9]{1}"))
						temp += contents.substring(t, t+1);
					}
					contents = temp;
				}
	
					edtUID.setText(contents);
	
					edtSecurityCode.requestFocus();
				
			} else if (resultCode == RESULT_CANCELED) {
				// Handle cancel
			}
		}
	}

	
	private View.OnClickListener btnScanClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
//			Intent mintent = new Intent();
//    		mintent = mintent.setClass(AddDeviceActivity.this,qr_codeActivity.class);
//    		AddDeviceActivity.this.startActivityForResult(mintent,REQUEST_CODE_GETUID_BY_SCAN_BARCODE );
			Intent qrcodeIntent = new Intent(AddDeviceActivity.this, CaptureActivity.class);
			startActivityForResult(qrcodeIntent, REQUEST_CODE_GETUID_BY_SCAN_BARCODE);
		}
	};

	private View.OnClickListener btnSearchOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(AddDeviceActivity.this, R.style.HoloAlertDialog));
			final AlertDialog dlg = builder.create();
			dlg.setTitle(getText(R.string.dialog_LanSearch));
			dlg.setIcon(android.R.drawable.ic_menu_more);

			LayoutInflater inflater = dlg.getLayoutInflater();
			View view = inflater.inflate(R.layout.search_device, null);
			dlg.setView(view);

			ListView lstSearchResult = (ListView) view.findViewById(R.id.lstSearchResult);
			Button btnRefresh = (Button) view.findViewById(R.id.btnRefresh);

			list.clear();
			st_LanSearchInfo[] arrResp = Camera.SearchLAN();

			if (arrResp != null && arrResp.length > 0) {
				for (st_LanSearchInfo resp : arrResp) {
					String sUID = new String(resp.UID).trim();
					boolean existed = checkUIDIsExist(sUID);
					list.add(new SearchResult(sUID, new String(resp.IP).trim(), (int) resp.port, existed));
				}
			}

			final SearchResultListAdapter adapter = new SearchResultListAdapter(dlg.getLayoutInflater());
			lstSearchResult.setAdapter(adapter);

			lstSearchResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

					SearchResult r = list.get(position);
					if( !r.isAlreadyAdded ) {
						edtUID.setText(r.UID);
						dlg.dismiss();
					}
				}
			});

			btnRefresh.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

					list.clear();
					st_LanSearchInfo[] arrResp = Camera.SearchLAN();

					if (arrResp != null && arrResp.length > 0) {
						for (st_LanSearchInfo resp : arrResp) {
							String sUID = new String(resp.UID).trim();
							boolean existed = checkUIDIsExist(sUID);
							list.add(new SearchResult(sUID, new String(resp.IP).trim(), (int) resp.port, existed));
						}
					}

					adapter.notifyDataSetChanged();
				}
			});

			dlg.show();
		}
	};

	private boolean checkUIDIsExist( String uid )
	{
		for (MyCamera camera : CameraList) {

			if (uid.equalsIgnoreCase(camera.getUID())) {
				return true;
			}
		}

		return false;
	}

	String dev_uid  = "";
	String dev_nickname ="";
	String view_pwd ="";
	private View.OnClickListener btnOKOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			dev_nickname = edtName.getText().toString();
			dev_uid = edtUID.getText().toString().trim();
			view_pwd = edtSecurityCode.getText().toString().trim();
			if (dev_nickname.length() == 0) {
				MainActivity.showAlert(AddDeviceActivity.this, getText(R.string.tips_warning), getText(R.string.tips_camera_name), getText(R.string.ok));
				return;
			}

			if (dev_uid.length() == 0) {
				MainActivity.showAlert(AddDeviceActivity.this, getText(R.string.tips_warning), getText(R.string.tips_dev_uid), getText(R.string.ok));
				return;
			}

			if (dev_uid.length() != 20) {
				MainActivity.showAlert(AddDeviceActivity.this, getText(R.string.tips_warning), getText(R.string.tips_dev_uid_character), getText(R.string.ok));
				return;
			}
			
			if (!dev_uid.matches("[a-zA-Z0-9]+")) 
			{
				MainActivity.showAlert(AddDeviceActivity.this, getText(R.string.tips_warning), getText(R.string.tips_dev_uid_special_characters), getText(R.string.ok));
				return;
			}
			
			if (view_pwd.length() == 0) {
				MainActivity.showAlert(AddDeviceActivity.this, getText(R.string.tips_warning), getText(R.string.tips_dev_security_code), getText(R.string.ok));
				return;
			}
			
			boolean duplicated = false;
			for (MyCamera camera : CameraList) {

				if (dev_uid.equalsIgnoreCase(camera.getUID())) {
					duplicated = true;
					break;
				}
			}

			if (duplicated) {
				MainActivity.showAlert(AddDeviceActivity.this, getText(R.string.tips_warning), getText(R.string.tips_add_camera_duplicated), getText(R.string.ok));
				return;
			}
			
			if (SplashScreenActivity.isCheckUid){
				pdialog = ProgressDialog.show(AddDeviceActivity.this, null, "Adding...",false,true);

				TenvisUtil tenvis = new TenvisUtil(AddDeviceActivity.this, handler);
				tenvis.setValue(dev_nickname, dev_uid, view_pwd);
				tenvis.exce();
			}else{
				goback(false);//不检测UID，直接添加
			}
		}
	};
	
	private void goback(boolean flg){

		//Agza mapping
		String udid = DatabaseManager.uid_Produce(AddDeviceActivity.this);
		AgzaPushUtil.mappingPush(AddDeviceActivity.this, dev_uid, null, "com.tutk.P2PCamLive", udid);
		Log.d("TPNS", "mapping");


		//Agza syncmapping
		List<String> UIDList = new ArrayList<String>();
		for(MyCamera camera : CameraList){
			UIDList.add(camera.getUID());
		}
		AgzaPushUtil.syncMapping(AddDeviceActivity.this,UIDList,"com.tutk.P2PCamLive",udid);
		Log.d("TPNS","syncmapping");

		//GCM TPNS
//		thread = new ThreadTPNS(AddDeviceActivity.this,dev_uid,0);
//		thread.start();
		
		int video_quality = 0;
		int channel = 0;
		/* add value to data base */
		DatabaseManager manager = new DatabaseManager(AddDeviceActivity.this);
		long db_id = manager.addDevice(dev_nickname, dev_uid, "", "", "admin", view_pwd, 3, channel);
		Toast.makeText(AddDeviceActivity.this, getText(R.string.tips_add_camera_ok).toString(), Toast.LENGTH_SHORT).show();
		/* return value to main activity */
		Bundle extras = new Bundle();
		extras.putLong("db_id", db_id);
		extras.putString("dev_nickname", dev_nickname);
		extras.putString("dev_uid", dev_uid);
		extras.putString("dev_name", "");
		extras.putString("dev_pwd", "");
		extras.putString("view_acc", "admin");
		extras.putString("view_pwd", view_pwd);
		extras.putInt("video_quality", video_quality);
		extras.putInt("camera_channel", 0);
		extras.putBoolean("flg", flg);

		Intent Intent = new Intent();
		Intent.putExtras(extras);
		AddDeviceActivity.this.setResult(RESULT_OK, Intent);
		AddDeviceActivity.this.finish();
	}
	
	
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what == 0){
				if(pdialog!=null){
					pdialog.dismiss();
					pdialog = null;
				}
				
				final String resultUID = msg.obj.toString();
				if(resultUID!=null && resultUID.contains("#")){
					String [] arr = resultUID.split("#");
					if(arr!=null && arr.length == 2){
						String new_uid = arr[0];
						String old_uid = arr[1];
						if(!old_uid.equals(new_uid)){
							dev_uid = new_uid;
							boolean duplicated = false;
							for (MyCamera camera : CameraList) {

								if (dev_uid.equalsIgnoreCase(camera.getUID())) {
									duplicated = true;
									break;
								}
							}

							if (duplicated) {
								MainActivity.showAlert(AddDeviceActivity.this, getText(R.string.tips_warning), getText(R.string.tips_add_camera_duplicated), getText(R.string.ok));
								return;
							}
							goback(true);
						}else{
							boolean duplicated = false;
							for (MyCamera camera : CameraList) {

								if (dev_uid.equalsIgnoreCase(camera.getUID())) {
									duplicated = true;
									break;
								}
							}

							if (duplicated) {
								MainActivity.showAlert(AddDeviceActivity.this, getText(R.string.tips_warning), getText(R.string.tips_add_camera_duplicated), getText(R.string.ok));
								return;
							}
							goback(false);
						}
					}
				}
			}
		};
	};
	
	private View.OnClickListener btnCancelOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			setResult(RESULT_CANCELED, intent);
			finish();
		}
	};


	private class SearchResult {

		public String UID;
		public String IP;
		public boolean isAlreadyAdded;
		// public int Port;

		public SearchResult(String uid, String ip, int port, boolean isAdded) {

			UID = uid;
			IP = ip;
			isAlreadyAdded = isAdded;
			// Port = port;
		}
	}

	private class SearchResultListAdapter extends BaseAdapter {

		private static final int TEXT_COLOR_NORMAL 	= 0xFF000000;
		private static final int TEXT_COLOR_GRAY 	= 0xFF999999;

		private LayoutInflater mInflater;

		public SearchResultListAdapter(LayoutInflater inflater) {

			this.mInflater = inflater;
		}

		public int getCount() {

			return list.size();
		}

		public Object getItem(int position) {

			return list.get(position);
		}

		public long getItemId(int position) {

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			final SearchResult result = (SearchResult) getItem(position);
			ViewHolder holder = null;

			if (convertView == null) {

				convertView = mInflater.inflate(R.layout.search_device_result, null);

				holder = new ViewHolder();
				holder.uid = (TextView) convertView.findViewById(R.id.uid);
				holder.ip = (TextView) convertView.findViewById(R.id.ip);

				convertView.setTag(holder);

			} else {

				holder = (ViewHolder) convertView.getTag();
			}

			int textColor = result.isAlreadyAdded ? TEXT_COLOR_GRAY : TEXT_COLOR_NORMAL;
			holder.uid.setTextColor( textColor );
			holder.uid.setText(result.UID);
			holder.ip.setTextColor( textColor );
			holder.ip.setText(result.IP);
			// holder.port.setText(result.Port);

			return convertView;
		}// getView()

		public final class ViewHolder {
			public TextView uid;
			public TextView ip;
		}
	}
	protected void onDestroy () 
	{
	    super.onDestroy(); 	
	    unregisterReceiver(resultStateReceiver);
	}
	
	private class ResultStateReceiver extends BroadcastReceiver 
	{
		@Override
		public void onReceive(Context context, Intent intent){
		}
	}

	
}
